package com.fh.auth.portal;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.jasig.cas.authentication.principal.Credentials;
import org.jasig.cas.authentication.principal.CredentialsToPrincipalResolver;
import org.jasig.cas.authentication.principal.Principal;
import org.jasig.cas.authentication.principal.SimplePrincipal;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.springframework.jdbc.core.JdbcTemplate;

public class PortalMoreInfoCredentialsToPrincipalResolver implements CredentialsToPrincipalResolver {
/*	private DataSource dataSource;

	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}*/

	private JdbcTemplate jdbcTemplate;  

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public Principal resolvePrincipal(Credentials credentials) {
		final UsernamePasswordCredentials usernamePasswordCredentials = (UsernamePasswordCredentials) credentials;
		String id = null;
		String userCode = null;
		String userName = null;
		String userTypeId = null;
		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			String username = usernamePasswordCredentials.getUsername();
			String password = usernamePasswordCredentials.getPassword();
			String sql = " select t.USER_ID,t.USER_CODE,t.USER_NAME,t.USER_TYPE_ID from sys_user t where t.USER_CODE=? and t.`PASSWORD`=? ";
			Object[] param = new Object[2];
			param[0] = username;
			param[1] = password;
			Map<String, Object> map = getJdbcTemplate().queryForMap(sql, param);
			if (map != null && map.size() > 0) {
				id = map.get("USER_ID")==null ? "" : String.valueOf(map.get("USER_ID"));
				userCode = map.get("USER_CODE")==null ? "" : String.valueOf(map.get("USER_CODE"));
				userName = map.get("USER_NAME")==null ? "" : String.valueOf(map.get("USER_NAME"));
				userTypeId = map.get("USER_TYPE_ID")==null ? "" : String.valueOf(map.get("USER_TYPE_ID"));
				returnMap.put("id", id);
				returnMap.put("userCode", URLEncoder.encode(userCode, "UTF-8"));
				returnMap.put("userName", URLEncoder.encode(userName, "UTF-8"));
				returnMap.put("userTypeId", userTypeId);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new SimplePrincipal(id, returnMap);
	}

	public boolean supports(Credentials credentials) {
		return credentials != null && UsernamePasswordCredentials.class.isAssignableFrom(credentials.getClass());
	}

}
